<template>
  <div class="container">
    <div class="watermark">众创空间入驻申请表</div>

    <div class="header">
      <h1>桂林电子科技大学科技园众创空间</h1>
      <h2>入 驻 申 请 书</h2>
      <div class="subtitle-container">
        <div class="subtitle-left">
          <span>申请时间：</span>
          <span class="date-display">{{ form.applicationDate }}</span>
        </div>
        <div class="subtitle-right">
          （适用于学生、教师、团队入驻申请）
        </div>
      </div>
    </div>

    <table style="table-layout: fixed;">
      <colgroup>
        <col style="width: 12%">
        <col style="width: 8%">
        <col style="width: 3%">
        <col style="width: 3%">
        <col style="width: 3%">
        <col style="width: 3%">
        <col style="width: 3%">
        <col style="width: 5%">
        <col style="width: 3%">
        <col style="width: 2%">
        <col style="width: 2%">
        <col style="width: 2%">
        <col style="width: 3%">
        <col style="width: 4%">
        <col style="width: 2%">
        <col style="width: 2%">
        <col style="width: 5%">
        <col style="width: 2%">
        <col style="width: 3%">
        <col style="width: 2%">
        <col style="width: 6%">
        <col style="width: 10%">
      </colgroup>

      <tbody>
      <tr>
        <td colspan="22">
          <strong>申请入驻团队/公司名称</strong>：<span>{{form.enterpriseName}} </span><span>（盖章）</span>
        </td>
      </tr>

      <tr>
        <td class="title-cell">申请人类型</td>
        <td colspan="21">
          <div class="checkbox-group">
            <div class="checkbox-item disabled">
              <span class="checkbox" :class="{checked: form.applicantType.includes('学生')}">✓</span>
              <span class="checkbox-label">学生</span>
            </div>
            <div class="checkbox-item disabled">
              <span class="checkbox" :class="{checked: form.applicantType.includes('教师')}">✓</span>
              <span class="checkbox-label">教师</span>
            </div>
            <div class="checkbox-item disabled">
              <span class="checkbox" :class="{checked: form.applicantType.includes('团队')}">✓</span>
              <span class="checkbox-label">团队</span>
            </div>
          </div>
        </td>
      </tr>

      <tr>
        <td class="title-cell">项目名称</td>
        <td colspan="21"><span class="readonly-text">{{ form.projectName }}</span></td>
      </tr>

      <tr>
        <td class="title-cell">联系人</td>
        <td colspan="2" class="text-center"><span class="readonly-text">{{ form.contactName }}</span></td>
        <td colspan="4" class="title-cell">联系方式</td>
        <td colspan="7" class="text-center"><span class="readonly-text">{{ form.contactPhone }}</span></td>
        <td colspan="4" class="title-cell">团队人数</td>
        <td colspan="4" class="text-center"><span class="readonly-text">{{ form.teamSize }}</span></td>
      </tr>

      <tr v-if="form.applicantType.includes('教师') || form.applicantType.includes('团队')">
        <td class="title-cell">是否备案</td>
        <td colspan="21">
          <div class="checkbox-group">
            <div class="checkbox-item disabled">
              <span class="checkbox" :class="{checked: form.isQualified === true}">✓</span>
              <span class="checkbox-label">是</span>
            </div>
            <div class="checkbox-item disabled">
              <span class="checkbox" :class="{checked: form.isQualified === false}">✓</span>
              <span class="checkbox-label">否</span>
            </div>
          </div>
        </td>
      </tr>

      <tr v-if="form.applicantType.includes('教师') || form.applicantType.includes('团队')">
        <td class="title-cell">注册资金</td>
        <td colspan="13" class="text-center">
          <div class="show-a-line">
            <span class="readonly-text">{{ form.registeredCapital }}</span>
            <span>元</span>
          </div>
        </td>
        <td colspan="4" class="title-cell">股权构成</td>
        <td colspan="4"><span class="readonly-text">{{ form.shareholdingRatio }}</span></td>
      </tr>

      <!-- 主要成员信息标题行 -->
      <tr>
        <td colspan="22" class="title-cell text-center">主要成员信息</td>
      </tr>
      <!-- 表头 -->
      <tr>
        <td class="title-cell">姓名</td>
        <td colspan="6" class="title-cell">学院/部门</td>
        <td colspan="5" class="title-cell">专业方向</td>
        <td colspan="4" class="title-cell">手机号码</td>
        <td colspan="4" class="title-cell">QQ号</td>
        <td colspan="2" class="title-cell">职务</td>
      </tr>
      <!-- 内容 -->
      <tr v-for="(member, index) in form.members" :key="index">
        <td><span class="readonly-text">{{ member.name }}</span></td>
        <td colspan="6"><span class="readonly-text">{{ member.department }}</span></td>
        <td colspan="5"><span class="readonly-text">{{ member.major }}</span></td>
        <td colspan="4"><span class="readonly-text">{{ member.phone }}</span></td>
        <td colspan="4"><span class="readonly-text">{{ member.qq }}</span></td>
        <td colspan="2"><span class="readonly-text">{{ member.job }}</span></td>
      </tr>

      <tr>
        <td rowspan="3" class="title-cell vertical-text">项目信息</td>
        <td colspan="4">项目简介</td>
        <td colspan="17"><span class="readonly-textarea">{{ form.projectDescription }}</span></td>
      </tr>

      <tr>
        <td colspan="4">所需帮助</td>
        <td colspan="17"><span class="readonly-textarea">{{ form.helpDescription }}</span></td>
      </tr>

      <tr>
        <td colspan="4">业务范围</td>
        <td colspan="17"><span class="readonly-textarea">{{ form.businessScope }}</span></td>
      </tr>

      <tr>
        <td class="title-cell vertical-text">承诺</td>
        <td colspan="21">
          <p style="line-height: 1.6; margin: 10px 0;">
            本团队(公司)承诺上述内容属实，如有任何虚假与隐瞒，本团队(公司)愿承担一切法律责任和后果。
          </p>
          <div style="display: flex; justify-content: space-between; margin-top: 20px;">
            <span>承诺人：<span class="readonly-text">{{ form.contactName }}</span></span>
            <span>签署日期：<span class="readonly-text">{{ form.applicationDate }}</span></span>
          </div>
        </td>
      </tr>

      <tr>
        <td class="title-cell vertical-text">审批意见</td>
        <td colspan="21">
          <div style="margin-bottom: 20px;">
            <strong>办公室主任意见：</strong>
            <span class="readonly-textarea">{{ form.officeOpinion }}</span>
          </div>
          <div>
            <strong>领导审批意见：</strong>
            <span class="readonly-textarea">{{ form.leaderOpinion }}</span>
          </div>
        </td>
      </tr>
      </tbody>
    </table>

    <div class="tip-box">
      <p><strong>注：</strong>请同时提供身份证、学生证/教师证、项目相关证明材料复印件。团队申请需提供团队成员身份证明。</p>
    </div>

    <div class="print-controls">
      <button class="print-btn" @click="printForm">打印申请表</button>
      <p class="print-tip">打印前请确保：1. 浏览器设置中启用了背景图形打印 2. 纸张方向为纵向 3. 页边距设置为默认</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute } from 'vue-router'
import { getApplicationFromId } from '@/api/enterpeise'
import type { AjaxResult } from '@/types/resultTypes'

const route = useRoute()

// 映射到 reactive form 对象
const form = reactive({
  applicationDate: '',
  enterpriseName: '',
  applicantType: [] as string[],
  projectName: '',
  contactName: '',
  contactPhone: '',
  teamSize: '',
  isQualified: null as boolean | null,
  registeredCapital: '',
  shareholdingRatio: '',
  members: [
    { name: '', department: '', major: '', phone: '', qq: '', job: '' },
    { name: '', department: '', major: '', phone: '', qq: '', job: '' },
    { name: '', department: '', major: '', phone: '', qq: '', job: '' },
    { name: '', department: '', major: '', phone: '', qq: '', job: '' },
    { name: '', department: '', major: '', phone: '', qq: '', job: '' },
    { name: '', department: '', major: '', phone: '', qq: '', job: '' },
    { name: '', department: '', major: '', phone: '', qq: '', job: '' }
  ],
  projectDescription: '',
  helpDescription: '',
  businessScope: '',
  officeOpinion: '',
  leaderOpinion: ''
})

// 定义填充表单的函数
const fillForm = (apiData: any) => {

  // 1. 直接映射的字段
  form.applicationDate = formatDate(apiData.applyDate) || '';
  form.enterpriseName = apiData.name || '';
  form.projectName = apiData.itemName || '';
  form.contactName = apiData.contactName || '';
  form.contactPhone = apiData.contactPhone || '';
  form.teamSize = apiData.numbers?.toString() || '';
  form.registeredCapital = apiData.registerMoney?.toString() || '';
  form.shareholdingRatio = apiData.shareholdingRatio || '';
  form.projectDescription = apiData.projectIntroduction || '';
  form.helpDescription = apiData.helpDescription || '';
  form.businessScope = apiData.businessScope || '';
  form.officeOpinion = apiData.officeOpinion || '';
  form.leaderOpinion = apiData.leaderOpinion || '';

  // 2. 需要转换的字段 - 申请人类型
  if (apiData.type !== undefined && apiData.type !== null) {
    const typeMapping: { [key: string]: string } = {
      '0': '学生',
      '1': '教师',
      '2': '团队'
    };
    const mappedType = typeMapping[apiData.type.toString()] || apiData.type;
    form.applicantType = [mappedType];
  } else {
    form.applicantType = [];
  }

  // 是否备案字段处理
  if (apiData.isQualified !== undefined && apiData.isQualified !== null) {
    form.isQualified = Boolean(apiData.isQualified);
  } else {
    form.isQualified = null;
  }

  // 3. 数组结构的映射 - 成员信息
  if (apiData.members && Array.isArray(apiData.members)) {
    form.members = apiData.members.map((apiItem: any, index: number) => {
      return {
        name: apiItem.name || '',
        department: apiItem.department || '',
        major: apiItem.major || '',
        phone: apiItem.phone || '',
        qq: apiItem.qq || '',
        job: apiItem.job || ''
      };
    });
    // 如果成员数量不足，用空对象填充
    while (form.members.length < 7) {
      form.members.push({ name: '', department: '', major: '', phone: '', qq: '', job: '' });
    }
  }
};

const getApplicationDetail = async (id: any) => {
  try {
    // 确保ID是BigInt类型
    let bigIntId;
    try {
      bigIntId = BigInt(id);
    } catch (error) {
      console.error('错误：ID无法转换为BigInt: ' + error);
      return;
    }

    // 修改API调用，传递BigInt ID
    const res = await getApplicationFromId(bigIntId) as unknown as AjaxResult<any>;

    if (res.code === 200) {
      // 调用填充表单的函数
      fillForm(res.data);
    } else {
      console.error('API返回错误:', res.msg);
      ElMessage.error(res.msg || '获取申请详情失败');
    }
  } catch (error) {
    console.error('获取申请详情失败: ' + error);
    ElMessage.error('获取申请详情失败');
  }
};

// 打印功能
const printForm = () => {
  window.print();
};


// 组件挂载时获取数据
onMounted(() => {
  const id = route.query.id;
  if (id) {
    getApplicationDetail(id);
    nextTick(() => {
      setTimeout(() => {
        window.print();
      }, 500);
    });
  } else {
    ElMessage.warning('缺少申请ID参数');
  }
});

// 将时间格式化函数 (统一转换为 YYYY 年 MM 月 DD 日 格式)
const formatDate = (dateString: string | null | undefined): string => {
  if (!dateString) return '';

  try {
    const date = new Date(dateString);
    if (isNaN(date.getTime())) return dateString; // 无效日期，直接返回原数据

    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().length === 1 ? '0' + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString();
    const day = date.getDate().toString().length === 1 ? '0' + date.getDate().toString() : date.getDate().toString();

    return `${year}年${month}月${day}日`;
  } catch (e) {
    console.warn('日期格式转换失败:', dateString, e);
    return '';
  }
};
</script>

<style scoped lang="scss">
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Microsoft YaHei", Arial, sans-serif;
}
body {
  padding: 20px;
  background-color: #f5f5f5;
  -webkit-print-color-adjust: exact;
  print-color-adjust: exact;
}

.header {
  text-align: center;
  margin-bottom: 20px;
}
.header h1 {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 10px;
  letter-spacing: 2px;
}
.header h2 {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  letter-spacing: 1px;
}
.subtitle-container {
  display: flex !important;
  justify-content: space-between !important;
  align-items: center !important;
  width: 100% !important;
  margin-bottom: 20px !important;
  min-height: 30px !important;
  position: relative !important;
  page-break-inside: avoid;
}
.subtitle-left {
  display: flex !important;
  align-items: center !important;
  flex: 0 0 auto !important;
  position: relative !important;
}
.subtitle-right {
  flex: 0 0 auto !important;
  text-align: right !important;
  position: relative !important;
  white-space: nowrap !important;
}
.date-display {
  font-size: 14px;
  margin-left: 5px;
}

.show-a-line {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
}
.enterprise-name {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
}

.enterprise-name textarea {
  flex: 1; /* 让<textarea>占据剩余空间 */
  margin-left: 8px; /* 添加一些左边距 */
}

.el-radio__inner {
  background-color: black;
  border-color: black ;
}
.container {
  max-width: 1200px;
  margin: 0 auto;
  background-color: white;
  padding: 30px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  position: relative;
}

.watermark {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) rotate(-45deg);
  font-size: 80px;
  color: rgba(0, 0, 0, 0.05);
  z-index: -1;
  font-weight: bold;
  text-transform: uppercase;
}

table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
  font-size: 14px;
  margin-bottom: 20px;
  min-width: 1000px;
  border: 1px solid #000;
}

td {
  border: 1px solid #000;
  height: 30px;
  padding: 4px 6px;
  vertical-align: top;
  word-break: break-all;
}

/* 强制表格边框完整 */
table, table tr, table td {
  border: 1px solid #000 !important;
}

table tr:last-child td {
  border-bottom: 1px solid #000 !important;
}

table td:last-child {
  border-right: 1px solid #000 !important;
}

table tr:first-child td {
  border-top: 1px solid #000 !important;
}

table td:first-child {
  border-left: 1px solid #000 !important;
}
.text-center {
  text-align: center;
}
.text-right {
  text-align: right;
}
.text-bold {
  font-weight: bold;
}
.title-cell {
  font-weight: bold;
  text-align: center;
}
.vertical-text {
  writing-mode: vertical-lr;
  text-align: center;
  margin: 0 auto;
  letter-spacing: 8px;
}
.checkbox-group {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}
.checkbox-item {
  display: flex;
  align-items: center;
  margin-right: 10px;
  white-space: nowrap;
  user-select: none;
}
.checkbox-item.disabled {
  cursor: default;
}
.checkbox-item.disabled:hover {
  background-color: transparent;
}
.checkbox {
  display: inline-block;
  width: 14px;
  height: 14px;
  border: 1px solid #000;
  margin-right: 4px;
  text-align: center;
  line-height: 12px;
  font-size: 10px;
  font-weight: bold;
  color: transparent;
  position: relative;
}
.checkbox.checked {
  color: #000;
  background-color: #fff;
}
.checkbox-label {
  font-size: 14px;
  margin-left: 2px;
}
.readonly-text {
  display: inline-block;
  width: 100%;
  min-height: 20px;
  line-height: 20px;
  font-size: 14px;
  word-break: break-all;
  white-space: normal;
}
.readonly-textarea {
  display: block;
  width: 100%;
  min-height: 60px;
  line-height: 1.4;
  font-size: 14px;
  word-break: break-word;
  white-space: pre-wrap;
}
.tip-box {
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  padding: 15px;
  margin-top: 20px;
  font-size: 14px;
  line-height: 1.6;
}
.tip-box p {
  margin-bottom: 10px;
}
.signature {
  text-align: right;
  padding-right: 20px;
  margin-top: 20px;
}
.print-controls {
  text-align: center;
  margin: 20px 0;
  padding: 15px;
  background: #e9f7fe;
  border-radius: 5px;
}
.print-btn {
  background: #1e88e5;
  color: white;
  border: none;
  padding: 10px 25px;
  font-size: 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.3s;
  margin-bottom: 10px;
}
.print-btn:hover {
  background: #0d47a1;
}
.print-tip {
  margin-top: 10px;
  color: #d32f2f;
  font-size: 14px;
}
@media print {
  body {
    padding: 0;
    background: none;
    margin: 0;
  }
  .container {
    box-shadow: none;
    padding: 0;
    max-width: 100%;
    margin: 0;
    overflow: visible !important;
    width: 100% !important;
  }
  .print-controls {
    display: none;
  }
  .watermark {
    display: none;
  }
  .subtitle-container {
    display: flex !important;
    justify-content: space-between !important;
    align-items: center !important;
    width: 100% !important;
    margin-bottom: 20px !important;
    page-break-inside: avoid;
  }
  .subtitle-left {
    display: flex !important;
    align-items: center !important;
    flex: 1 !important;
  }
  .subtitle-right {
    text-align: right !important;
    flex: 1 !important;
  }

  /* 确保表格在纵向打印时完整显示 */
  @page {
    size: A4 portrait;
    margin: 0.8cm;
  }

  /* 表格打印样式 */
table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
  font-size: 14px;
  margin-bottom: 20px;
  min-width: 1000px;
  border: 1px solid #000;
}

  /* 调整列宽以适应纵向打印 - 不使用缩放 */
  colgroup col {
    width: auto !important;
  }

  /* 重新定义列宽比例 - 确保总和为100% */
  colgroup col:nth-child(1) { width: 7% !important; }
  colgroup col:nth-child(2) { width: 5% !important; }
  colgroup col:nth-child(3) { width: 3% !important; }
  colgroup col:nth-child(4) { width: 3% !important; }
  colgroup col:nth-child(5) { width: 3% !important; }
  colgroup col:nth-child(6) { width: 3% !important; }
  colgroup col:nth-child(7) { width: 3% !important; }
  colgroup col:nth-child(8) { width: 4% !important; }
  colgroup col:nth-child(9) { width: 3% !important; }
  colgroup col:nth-child(10) { width: 2% !important; }
  colgroup col:nth-child(11) { width: 2% !important; }
  colgroup col:nth-child(12) { width: 2% !important; }
  colgroup col:nth-child(13) { width: 3% !important; }
  colgroup col:nth-child(14) { width: 4% !important; }
  colgroup col:nth-child(15) { width: 2% !important; }
  colgroup col:nth-child(16) { width: 2% !important; }
  colgroup col:nth-child(17) { width: 4% !important; }
  colgroup col:nth-child(18) { width: 2% !important; }
  colgroup col:nth-child(19) { width: 3% !important; }
  colgroup col:nth-child(20) { width: 2% !important; }
  colgroup col:nth-child(21) { width: 5% !important; }
  colgroup col:nth-child(22) { width: 8% !important; }

  /* 确保所有单元格都有边框 */
  td {
    border: 1px solid #000 !important;
    -webkit-print-color-adjust: exact !important;
    print-color-adjust: exact !important;
    page-break-inside: avoid !important;
    padding: 1px 2px !important;
    vertical-align: middle !important;
    font-size: 10px !important;
    line-height: 1.1 !important;
    word-wrap: break-word !important;
    overflow-wrap: break-word !important;
  }

  /* 强制表格边框 */
  table, table tr, table td {
    border: 1px solid #000 !important;
  }

  /* 确保最右边的边框 */
  table td:last-child {
    border-right: 1px solid #000 !important;
  }

  /* 确保最下面的边框 */
  table tr:last-child td {
    border-bottom: 1px solid #000 !important;
  }

  /* 确保表格容器不会截断边框 */
  .container {
    overflow: visible !important;
    width: 100% !important;
  }

  /* 确保输入框在打印时正确显示 */
  input[type="text"],
  input[type="date"],
  textarea {
    border: none !important;
    background: transparent !important;
    -webkit-print-color-adjust: exact !important;
    print-color-adjust: exact !important;
    font-size: 12px !important;
  }

  /* 调整标题字体大小 */
  .header h1 {
    font-size: 18px !important;
    margin-bottom: 8px !important;
  }
  .header h2 {
    font-size: 16px !important;
    margin-bottom: 12px !important;
  }

  /* 调整复选框大小 */
  .checkbox {
    width: 12px !important;
    height: 12px !important;
    line-height: 10px !important;
    font-size: 8px !important;
  }

  .checkbox-label {
    font-size: 12px !important;
  }

  /* 调整垂直文字 */
  .vertical-text {
    font-size: 12px !important;
    letter-spacing: 4px !important;
  }

  /* 调整提示框 */
  .tip-box {
    font-size: 12px !important;
    padding: 10px !important;
    margin-top: 10px !important;
  }

  /* 强制表格不换页 */
  tr {
    page-break-inside: avoid !important;
  }
}
</style>
